package com.mqqzt.douban.util;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.google.gdata.client.douban.DoubanService;
import com.mqqzt.douban.R;
import com.mqqzt.douban.domain.NewBook;

public class NetUtil {
	public static String isNeedaptcha(Context context) throws Exception{
		String loginurl = context.getResources().getString(R.string.loginurl);
		URL url = new URL(loginurl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		Source source = new Source(conn);
		List<Element> elements = source.getAllElements("input");
		for(Element element : elements){
			String result = element.getAttributeValue("name");
			if("captcha-id".equals(result)){
				return element.getAttributeValue("value");
			}
		}
		return null;
	}
	
	public static Bitmap getImage(String path) throws Exception{
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		InputStream is = conn.getInputStream();
		return BitmapFactory.decodeStream(is);
	}
	
	public static boolean Login(String name, String pwd, String captcha, String captchaid, Context context) throws Exception{
		String apiKey = "0c51c1ba21ad8cfd24f5452e6508a6f7";
		String secret = "359e16e5e5c62b6e";

		DoubanService myService = new DoubanService("黑马小瓣瓣", apiKey,
				secret);

		System.out.println("please paste the url in your webbrowser, complete the authorization then come back:");
		String url = myService.getAuthorizationUrl(null);
		String oauth_token = url.substring(url.lastIndexOf("=") + 1, url.length());
		System.out.println(url);
		
		HttpPost post = new HttpPost("http://www.douban.com/accounts/login");
		List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		parameters.add(new BasicNameValuePair("source", "simple"));
		parameters.add(new BasicNameValuePair("redir", "http://www.douban.com"));
		parameters.add(new BasicNameValuePair("form_email", name));
		parameters.add(new BasicNameValuePair("form_password", pwd));
		parameters.add(new BasicNameValuePair("user_login", "登录"));
		parameters.add(new BasicNameValuePair("captcha-solution", captcha));
		parameters.add(new BasicNameValuePair("captcha-id", captchaid));
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
		post.setEntity(entity);
		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = client.execute(post);
//		Source source = new Source(response.getEntity().getContent());
//		System.out.println(source.toString());
		System.out.println(response.getStatusLine().getStatusCode());
		CookieStore cookie = client.getCookieStore();
		
		HttpPost post1 = new HttpPost(url);
		
		List<NameValuePair> parameters1 = new ArrayList<NameValuePair>();
		parameters1.add(new BasicNameValuePair("ck", "eq9w"));
		parameters1.add(new BasicNameValuePair("oauth_token", oauth_token));
		parameters1.add(new BasicNameValuePair("oauth_callback", ""));
		parameters1.add(new BasicNameValuePair("ssid", "225a1ec8"));
		parameters1.add(new BasicNameValuePair("confirm", "同意"));
		UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(parameters1, "utf-8");
		post1.setEntity(entity1);
		DefaultHttpClient client1 = new DefaultHttpClient();
		client1.setCookieStore(cookie);
		client1.execute(post1);
		ArrayList<String> accessToken = myService.getAccessToken();
		String accesstoken = accessToken.get(0);
		String tokensecret = accessToken.get(1);
		System.out.println(accesstoken);
		System.out.println(tokensecret);
		SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
		Editor editor = sp.edit();
		editor.putString("accesstoken", accesstoken);
		editor.putString("tokensecret", tokensecret);
		editor.commit();
		return true;
	}
	
	public static List<NewBook> getNewBooks(Context context) throws Exception{
		String path = context.getResources().getString(R.string.newbookpath);
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		Source source = new Source(conn);
		List<Element> liElements = source.getAllElements("li");
		List<NewBook> books = new ArrayList<NewBook>();
		for(Element liElement : liElements){
			List<Element> liChildrenLists = liElement.getChildElements();
			if(liChildrenLists.size() == 2){
				if("detail-frame".equals(liChildrenLists.get(0).getAttributeValue("class"))){
					NewBook newBook = new NewBook();
					Element div = liChildrenLists.get(0);
					List<Element> divChildrenLists = div.getChildElements();
					String name = divChildrenLists.get(0).getTextExtractor().toString();
					newBook.setName(name);
					String description = divChildrenLists.get(1).getTextExtractor().toString();
					newBook.setDescription(description);
					String summary = divChildrenLists.get(2).getTextExtractor().toString();
					newBook.setSummary(summary);
					
					Element a = liChildrenLists.get(1);
					List<Element> aChildrenLists = a.getChildElements();
					String imagepath = aChildrenLists.get(0).getAttributeValue("src");
					newBook.setImagePath(imagepath);
					books.add(newBook);
				}
			}
		}
		return books;
	}
}
